<template>
  <div>
    <div class="head-bar flex mb_10">
      <!-- 有商品分类展示商品分类 -->
      <template v-if="route.query.categoryId">
        <!-- 头部展示筛选信息 -->
        <div @click="cateClick(tabBar,1)">{{ tabBar.name }}</div>
        <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24">
          <path fill="#999999" d="m13.172 12l-4.95-4.95l1.414-1.413L16 12l-6.364 6.364l-1.414-1.415z"/>
        </svg>

        <div class="bar" v-if="tabBar.first">{{ tabBar.first.name }}
          <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24"><path fill="#999999" d="m12 13.171l4.95-4.95l1.414 1.415L12 16L5.636 9.636L7.05 8.222z"/></svg>
          <ul><li v-for="item in tabBar.children" :key="item.id"  @click="cateClick(item,2)">{{ item.name }}</li></ul>
        </div>
        <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" v-if="tabBar.first">
          <path fill="#999999" d="m13.172 12l-4.95-4.95l1.414-1.413L16 12l-6.364 6.364l-1.414-1.415z"/>
        </svg>

        <div class="bar" v-if="tabBar.second">{{ tabBar.second.name }}
          <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24"><path fill="#999999" d="m12 13.171l4.95-4.95l1.414 1.415L12 16L5.636 9.636L7.05 8.222z"/></svg>
          <ul><li v-for="item in tabBar.first.children" :key="item.id"  @click="cateClick(item,3)">{{ item.name }}</li></ul>
        </div>
        <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" v-if="tabBar.second"><path fill="#999999" d="m13.172 12l-4.95-4.95l1.414-1.413L16 12l-6.364 6.364l-1.414-1.415z"/></svg>

      </template>
      <!-- 无商品分类，展示搜索结果 -->
      <template v-else>
        <div>全部结果 </div>
        <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24">
          <path fill="#999999" d="m13.172 12l-4.95-4.95l1.414-1.413L16 12l-6.364 6.364l-1.414-1.415z"/>
        </svg>
        <div class="ml_10">“{{apiParams.keyword}}”</div>
      </template>
      <!--所选分类-->
      <a class="selected-item" @click="cancelSelected(item, index)" v-for="(item, index) in selectedItem" :key="index" :title="item.name">
        <span>{{ item.type }}：</span><span>{{ item.name }}</span>&nbsp;
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
          <path fill="#ef4444" d="m12 10.587l4.95-4.95l1.414 1.414l-4.95 4.95l4.95 4.95l-1.415 1.414l-4.95-4.95l-4.949 4.95l-1.414-1.415l4.95-4.95l-4.95-4.95L7.05 5.638z"/>
        </svg>
      </a>
    </div>

    <!--筛选主体-->
    <div class="screening-subject">
      <!-- 品牌， 有图片，独立出来 -->
      <div class="other brand" v-show="tagsContent[0].show && tagsContent[0].values.length">
        <div>{{ tagsContent[0].key }}：</div>
        <div>
          <ul :class="{ 'show-more': tagsContent[0].more }">
            <li @click="selectBrand(item.name, 0)" :class="{ 'border-color': multSelected.includes(item) }" v-for="(item, index) in tagsContent[0].values" :key="index">
              <img :src="item.url" alt="" /><span>{{ item.name }}</span>
              <div class="corner-icon" v-show="multSelected.includes(item.name)">
                <div>
                  <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" class="icon">
                    <path fill="#ffffff" d="m10 15.17l9.192-9.191l1.414 1.414L10 17.999l-6.364-6.364l1.414-1.414z"/>
                  </svg>
                </div>
              </div>
            </li>
          </ul>
          <div class="btn" v-show="multiple !== 0">
            <span @click="moreBrand(0)">{{ tagsContent[0].more ? "收起" : "更多"}}
              <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" v-if="tagsContent[0].more">
                <path fill="#999999" d="m12 10.828l-4.95 4.95l-1.414-1.414L12 8l6.364 6.364l-1.414 1.414z"/>
              </svg>
              <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" v-else>
                <path fill="#999999" d="m12 13.171l4.95-4.95l1.414 1.415L12 16L5.636 9.636L7.05 8.222z"/>
              </svg>
            </span>
            <span @click="multSelectBrand(0)">
              <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24"><path fill="#999999" d="M11 11V5h2v6h6v2h-6v6h-2v-6H5v-2z"/></svg>多选
            </span>
          </div>
          <div class="multBtn" v-show="multiple === 0">
            <a-button status="warning" type="outline" size="mini" class="mr_10" :disabled="!multSelected.length" @click="sure(0)">确定</a-button>
            <a-button status="warning" type="outline" size="mini" class="mr_10" @click="cancel">取消</a-button>
          </div>
        </div>
      </div>
      <!-- 其他筛选项 -->
      <template v-for="(tag, tagIndex) in tagsContent">
        <div class="other" v-if="tag.show && tagIndex !== 0" v-show="tagIndex < showTagCount" :key="tagIndex">
          <div>{{ tag.key }}：</div>
          <div>
            <ul :class="{ 'show-more': tag.more }" class="list" v-show="multiple !== tagIndex">
              <li @click="selectBrand(item, tagIndex)" class="item" v-for="(item, index) in tag.values" :key="index">{{ item }}</li>
            </ul>
            <a-checkbox-group class="list mt_10" v-model="multSelected"  v-show="multiple === tagIndex" :class="{ 'show-more': tag.more }">
              <a-checkbox class="item" v-for="(item, index) in tag.values" :key="index" :value="item">{{ item }}</a-checkbox>
            </a-checkbox-group>
            <div class="btn" v-show="multiple !== tagIndex">
              <span @click="moreBrand(tagIndex)" v-show="tag.values.length > 9">{{ tag.more ? "收起" : "更多"}}
                <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" v-if="tagsContent[0].more">
                  <path fill="#999999" d="m12 10.828l-4.95 4.95l-1.414-1.414L12 8l6.364 6.364l-1.414 1.414z"/>
                </svg>
                <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" v-else>
                  <path fill="#999999" d="m12 13.171l4.95-4.95l1.414 1.415L12 16L5.636 9.636L7.05 8.222z"/>
                </svg>
              </span>
              <span @click="multSelectBrand(tagIndex)">
                <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24"><path fill="#999999" d="M11 11V5h2v6h6v2h-6v6h-2v-6H5v-2z"/></svg>多选
              </span>
            </div>
            <div class="multBtn" v-show="multiple === tagIndex">
              <a-button status="warning" type="outline" size="mini" class="mr_10" :disabled="!multSelected.length" @click="sure(tagIndex)">确定</a-button>
              <a-button status="warning" type="outline" size="mini" class="mr_10" @click="cancel">取消</a-button>
            </div>
          </div>
        </div>
      </template>

    </div>


  </div>
</template>

<script setup lang="ts">
  import { ref, watch, onMounted, computed } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { useUserStore } from '@/stores/user';
  import { storeToRefs } from 'pinia';
  import { filterList } from "@/api/goods";

  const route = useRoute();
  const router = useRouter();
  // 状态管理
  const store = useUserStore();
  const { category } = storeToRefs(store);

  // 请求参数
  const apiParams = ref<any>({});
  // 标签
  const tagsContent = ref<any>([
    { key: '品牌', more: false, show: true, values: [] }
  ]);
  // 分类数据
  const tabBar = ref<any>({ name: '', first: {}, second: {}});
  // 已选分类集合 顶部展示
  const selectedItem = ref<Array<any>>([]);
  // 品牌id合集
  const brandIds = ref<Array<any>>([]);
  // 多选
  const multiple = ref<boolean | number>(false);
  // 多选分类
  const multSelected = ref<any>([]);
  // 展示的搜索项数量
  const showTagCount = ref(5);

  const emit = defineEmits(['getParams']);


  // 筛选、分类  列表
  const getFilterList = () => {
    filterList(apiParams.value).then((res) => {
      if (res.data && res.data.success) {
        const data = res.data.result;
        tagsContent.value = [{ key: '品牌', more: false, show: true, values: [] }];
        tagsContent.value[0].values = data.brands;
        tagsContent.value = tagsContent.value.concat(data.paramOptions);
        tagsContent.value.forEach((item: any) => {
          item.show = true;
          item.more = false;
        });
      }
    });
  };
  // 商品分类
  const cateList = computed(() => {
    return category.value || [];
  }) as any;
  // 获取商品分类，分类下展示
  const getNav = () => {
    if (!route.query.categoryId) return;
    // 商品分类存储在localstorage，接口未调用成功前再次刷新数据
    if (!cateList.value.length) {
      setTimeout(() => { getNav() }, 500);
      return;
    }
    const arr = route.query.categoryId.split(',');
    if (arr.length > 0) {
      tabBar.value = JSON.parse(cateList.value).filter((e: any) => {return e.id === arr[0]})[0];
    }
    if (arr.length > 1) {
      const firstData = tabBar.value.children.filter((e: any) => {return e.id === arr[1]})[0];
      tabBar.value.first = firstData;
    } else {
      tabBar.value.first = tabBar.value.children[0];
    }
    if (arr.length > 2) {
      const secondData = tabBar.value.first.children.filter((e: any) => {return e.id === arr[2]})[0];
      tabBar.value.second = secondData;
    } else {
      tabBar.value.second = tabBar.value.first.children[0];
    }
  };
  // 点选分类
  const cateClick = (item: any, index: any) => {
    // router.push({path: '/goodsList'});
    // router.go(0);
    // window.location.reload();
    if (index === 1) {
      router.push({path: '/goodsList', query: {categoryId: item.id}});
      // window.location.reload();
    } else if (index === 2) {
      router.push({path: '/goodsList', query: {categoryId: [item.parentId, item.id].toString()}});
      // window.location.reload();
    } else if (index ===3) {
      router.push({path: '/goodsList', query: {categoryId: [tabBar.value.id, item.parentId, item.id].toString()}});
      // window.location.reload();
    }
  };


  // 选择筛选项
  const selectBrand = (item: any, index: any) => {
    // 非多选直接在顶部栏展示，多选则添加选择状态
    if (multiple.value !== false) {
      let key = multSelected.value.indexOf(item);
      if (key > -1) {
        multSelected.value.splice(key, 1);
      } else {
        multSelected.value.push(item);
      }
    } else {
      selectedItem.value.push({ type: tagsContent.value[index].key, name: item });
      tagsContent.value[index].show = false;
      if (index === 0) {
        // 如果是品牌，获取品牌id
        let brands = tagsContent.value[0].values;
        brands.forEach((val: any) => {
          if (val.name === item) brandIds.value.push(val.value);
        });
      }
    }
  };
  // 顶部栏 取消已选中的项
  const cancelSelected = (item: any, index: any) => {
    selectedItem.value.splice(index, 1);
    tagsContent.value.forEach((tag: any) => {
      if (tag.key === item.type) {
        tag.show = true;
        tag.more = false;
      }
    });
    if (item.type === '品牌') {
      brandIds.value = [];
    }
  };
  // 更多按钮
  const moreBrand = (index: any) => {
    const flag = !tagsContent.value[index].more;
    tagsContent.value[index].more = flag;
  };
  // 多选按钮
  const multSelectBrand = (index: any) => {
    tagsContent.value[index].more = true;
    multiple.value = index;
  };
  // 多选确认按钮
  const sure = (index: any) => {
    selectedItem.value.push({
      type: tagsContent.value[index].key,
      name: multSelected.value.join('、')
    });
    if (index === 0) {
      // 如果是品牌，获取品牌id
      let brands = tagsContent.value[0].values;
      brands.forEach((val: any) => {
        if (multSelected.value.includes(val.name)) brandIds.value.push(val.value);
      });
    }
    tagsContent.value[index].show = false;
    cancel();
  };
  // 多选取消按钮
  const cancel = () => {
    multSelected.value = [];
    tagsContent.value[0].more = false;
    multiple.value = false;
  };


  onMounted(() => {
    // 有分类id就根据id搜索
    if (route.query.categoryId) {
      let cateId = route.query.categoryId.split(',');
      Object.assign(apiParams.value, route.query);
      apiParams.value.categoryId = cateId[cateId.length - 1];
    } else {
      Object.assign(apiParams.value, route.query);
    }
    getFilterList();
    getNav();
  });

  watch(() => selectedItem.value,
    (val: any) => {
      // 监听已选条件，来调用列表接口
      let classification = [] as any;
      apiParams.value.brandId = '';
      apiParams.value.prop = '';
      val.forEach((item: any) => {
        if (item.type === '品牌') {
          apiParams.value.brandId = brandIds.value.join('@');
        } else {
          const nameArr = item.name.split('、');
          nameArr.forEach((name: any) => {
            classification.push(item.type + '_' + name);
          });
        }
      });
      apiParams.value.prop = classification.join('@');
      getFilterList();
      emit('getParams', apiParams.value);
    }, { deep: true }
  );
  // 监听分类id改变
  watch(() => route.query.categoryId, (val) => {
    if (route.query.categoryId) {
      let cateId = route.query.categoryId.split(',');
      Object.assign(apiParams.value, route.query);
      apiParams.value.categoryId = cateId[cateId.length - 1]
    } else {
      Object.assign(apiParams.value, route.query);
    }
    getFilterList();
    getNav();
  });
  // 监听商品关键字改变
  watch(() => route.query.keyword, (val) => {
    apiParams.value.keyword = val;
    getFilterList();
  })
</script>

<style scoped lang="less">
  // 头部展示筛选项
  .head-bar {
    background-color: #ffffff;
    box-sizing: border-box;
    padding: 10px 20px;
    font-size: 14px;
    align-items: center;
    //所选分类
    .selected-item {
      font-size: 12px;
      color: #333333;
      padding: 0 6px;
      margin: 0 5px;
      max-width: 250px;
      height: 24px;
      line-height: 24px;
      overflow: hidden;
      position: relative;
      background-color: #f3f3f3;
      border: 1px solid #ddd;
      display: flex;
      align-items: center;
      cursor: pointer;
      &:hover {
        border-color: @theme_color;
        background-color: #fff;
      }
      span:nth-child(2) {
        color: @theme_color;
      }
    }
  }

  // 头部展示筛选项（有商品分类展示商品分类）
  .bar {
    font-size: 12px;
    position: relative;
    background: #fff;
    border: 1px solid #999;
    padding: 3px 0 0;
    min-width: 85px;
    text-align: center;
    margin: 0 3px;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1;
    &:hover {
      color: @theme_color;
      border-color: @theme_color;
      border-bottom-color: #fff;
      cursor: pointer;
      ul {
        display: block;
      }
      .ivu-icon {
        transform: rotate(180deg);
      }
    }
    ul {
      display: none;
      position: absolute;
      top: 17px;
      left: -1px;
      width: 260px;
      padding: 5px 10px;
      background: #fff;
      border: 1px solid @theme_color;
      z-index: 10;
      margin: 0;
      list-style: none;
      &::before {
        content: "";
        position: absolute;
        width: 86px;
        left: 0;
        top: -1px;
        z-index: 2;
        border-top: 1px solid #fff;
      }
      &:hover {
        display: block;
      }
      clear: left;
      li {
        color: #999;
        float: left;
        width: 33%;
        margin: 3px 0;
        text-align: left;
        &:hover {
          color: @theme_color;
          cursor: pointer;
        }
      }
    }
  }

  // 筛选主体
  .screening-subject {
    border-top: 1px solid @light_border_color;
    background-color: #f1f2f3;
    .other {
      display: flex;
      align-items: center;
      border-bottom: 1px solid @light_border_color;
      > div:nth-of-type(1) {
        width: 100px;
        text-align: right;
        box-sizing: border-box;
        padding-right: 10px;
      }
      > div:nth-of-type(2) {
        width: 1100px;
        background-color: #ffffff;
        position: relative;
        min-height: 35px;
        ul.list {
          width: 900px;
          max-height: 100px;
          overflow: hidden;
          padding-top: 1px;
          clear: left;
          list-style: none;
          margin: 0 0 0 -20px;
          li.item {
            width: 100px;
            height: 30px;
            float: left;
            line-height: 30px;
            color:#4d9cf1;
            overflow: hidden;
            position: relative;
            font-size: 12px;
            padding: 2px;
            cursor: pointer;
            &:hover {
              color: @theme_color;
            }
          }
        }
        .btn {
          position: absolute;
          right: 10px;
          top: 8px;
          display: flex;
          span {
            border: 1px solid #ddd;
            margin-left: 10px;
            color: @light_text_color;
            padding: 3px 3px;
            font-size: 12px;
            line-height: 12px;
            display: flex;
            align-items: flex-end;
            &:hover {
              cursor: pointer;
              color: @theme_color;
              border-color: @theme_color;
            }
          }
        }
        .multBtn {
          text-align: center;
          margin-top: 10px;
          margin-bottom: 10px;
          .arco-btn {
            font-size: 12px !important;
          }
          .arco-btn:last-child {
            margin-left: 10px;
          }
        }
      }
    }
    .brand {
      > div:nth-of-type(2) {
        > ul {
          width: 960px;
          max-height: 112px;
          overflow: hidden;
          clear: left;
          list-style: none;
          margin-left: -20px;
          li {
            width: 100px;
            height: 50px;
            float: left;
            border: 1px solid #ddd;
            margin: 1px;
            overflow: hidden;
            position: relative;
            padding: 1px;
            text-align: center;
            line-height: 50px;
            color: #666666;
            cursor: pointer;
            img {
              width: 100%;
              height: 100%;
            }
            &:hover {
              border-color: @theme_color;
              border: 1px solid @theme_color;
              top: 0;
              left: 0;
              position: relative;
              z-index: 1;
              img {
                display: none;
              }
            }
            .corner-icon {
              position: absolute;
              right: -1px;
              bottom: -1px;
              div {
                width: 0;
                border-top: 22px solid transparent;
                border-right: 22px solid @theme_color;
              }
              .icon {
                font-size: 12px;
                position: absolute;
                bottom: 0;
                right: 0;
                transform: rotate(-15deg);
                color: #fff;
              }
            }
          }
        }
        .show-more {
          height: auto;
          max-height: 200px;
          overflow-y: scroll;
        }
      }
    }
  }
</style>
